package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.*;
import com.dropdb.demo.bean.vo.*;
import com.dropdb.demo.mapper.*;
import com.dropdb.demo.service.AdminMarketService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.System;
import java.util.*;

/**
 * @author Alone
 * @version 1.0
 * @date 2020/6/26 20:24
 */
@Service
public class AdminMarketServiceImpl implements AdminMarketService {
    @Autowired
    RegionMapper regionMapper;
    @Autowired
    BrandMapper brandMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    IssueMapper issueMapper;
    @Autowired
    KeywordMapper keywordMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public List<MarketRegionListVO> queryRegions() {
        RegionExample regionExample = new RegionExample();
        regionExample.createCriteria().andPidEqualTo(0);
        List<Region> provinces = regionMapper.selectByExample(regionExample);
        List<MarketRegionListVO> vos = new ArrayList<>();
        for (Region province : provinces) {
            RegionExample cityExample = new RegionExample();
            cityExample.createCriteria().andPidEqualTo(province.getId());
            List<Region> cities = regionMapper.selectByExample(cityExample);
            List<MarketRegionCityVO> cityVOS = new ArrayList<>();

            for (Region city : cities) {
                RegionExample areaExample = new RegionExample();
                areaExample.createCriteria().andPidEqualTo(city.getId());
                List<Region> areas = regionMapper.selectByExample(areaExample);
                List<MarketRegionAreaVO> areaVOS = new ArrayList<>();

                for (Region area : areas) {
                    areaVOS.add(new MarketRegionAreaVO(area.getId(), area.getName(),
                            area.getType(), area.getCode()));
                }
                cityVOS.add(new MarketRegionCityVO(city.getId(), city.getName(),
                        city.getType(), city.getCode(), areaVOS));
            }
            vos.add(new MarketRegionListVO(province.getId(), province.getName(),
                    province.getType(), province.getCode(), cityVOS));
        }
        return vos;
    }

    @Override
    public MarketBaseDataVO queryBrands(Integer page, Integer limit, String sort, String order, Integer id, String name) {
        BrandExample brandExample = new BrandExample();
        BrandExample.Criteria criteria = brandExample.createCriteria();
        if (id != null) {
            criteria.andIdEqualTo(id);
        }
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        brandExample.setOrderByClause(sort + " " + order);

        //执行查询前使用分页
        PageHelper.startPage(page, limit);
        List<Brand> brands = brandMapper.selectByExample(brandExample);
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);
        long total = pageInfo.getTotal();
        return new MarketBaseDataVO(brands, total);
    }

    @Override
    public Brand createBrand(Brand bo) {
        bo.setAddTime(new Date(System.currentTimeMillis()));
        bo.setUpdateTime(new Date(System.currentTimeMillis()));
        brandMapper.insertSelective(bo);
        return bo;
    }

    @Override
    public Brand updateBrand(Brand brand) {
        brand.setUpdateTime(new Date(System.currentTimeMillis()));
        brandMapper.updateByPrimaryKey(brand);
        return brandMapper.selectByPrimaryKey(brand.getId());
    }

    @Override
    public void deleteBrand(Brand brand) {
        brand.setDeleted(true);
        brand.setUpdateTime(new Date(System.currentTimeMillis()));
        brandMapper.updateByPrimaryKeySelective(brand);
        //brandMapper.deleteByPrimaryKey(brand.getId());
    }

    @Override
    public MarketBaseDataVO queryOrders(Integer page, Integer limit, String sort, String order, Short[] orderStatusArray, Integer userId, String orderSn) {
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        if (orderStatusArray != null) {
            criteria.andOrderStatusIn(Arrays.asList(orderStatusArray));
        }
        if (userId != null) {
            criteria.andUserIdEqualTo(userId);
        }
        if (orderSn != null && !orderSn.equals("")) {
            criteria.andOrderSnEqualTo(orderSn);
        }
        criteria.andDeletedEqualTo(false);
        orderExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);
        List<Order> orders = orderMapper.selectByExample(orderExample);
        PageInfo<Order> pageInfo = new PageInfo<>(orders);
        long total = pageInfo.getTotal();
        return new MarketBaseDataVO(orders, total);
    }

    @Override
    public MarketOrderDetailVO orderDetail(Integer id) {
        Order order = orderMapper.selectByPrimaryKey(id);

        OrderGoodsExample orderGoodsExample = new OrderGoodsExample();
        orderGoodsExample.createCriteria().andOrderIdEqualTo(id).andDeletedEqualTo(false);
        List<OrderGoods> orderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        User user = userMapper.selectByPrimaryKey(order.getUserId());

        MarketOrderDetailVO vo = new MarketOrderDetailVO();
        vo.setOrder(order);
        vo.setOrderGoods(orderGoods);
        vo.setUser(user.getAvatar(),user.getNickname());
        return vo;
    }

    @Override
    public Order orderRefund(Map bo) {
        Order o = new Order();
        o.setId((Integer) bo.get("orderId"));
        o.setOrderStatus((short) 203);
        o.setUpdateTime(new Date(System.currentTimeMillis()));
        orderMapper.updateByPrimaryKeySelective(o);
        Order order = orderMapper.selectByPrimaryKey(o.getId());
        return order;
    }

    @Override
    public Order orderShip(Map bo) {
        Order order = new Order();
        order.setId((Integer) bo.get("orderId"));
        order.setShipChannel((String) bo.get("shipChannel"));
        order.setShipSn((String) bo.get("shipSn"));
        order.setOrderStatus((short) 301);
        order.setUpdateTime(new Date(System.currentTimeMillis()));
        orderMapper.updateByPrimaryKeySelective(order);
        orderMapper.selectByPrimaryKey(order.getId());
        return order;
    }

    @Override
    public MarketBaseDataVO queryIssues(Integer page, Integer limit, String sort, String order, String question) {
        IssueExample issueExample = new IssueExample();
        IssueExample.Criteria criteria = issueExample.createCriteria();
        if (question != null) {
            criteria.andQuestionLike("%" + question + "%");
        }
        criteria.andDeletedEqualTo(false);
        issueExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);
        List<Issue> issues = issueMapper.selectByExample(issueExample);
        PageInfo<Issue> pageInfo = new PageInfo<>(issues);
        long total = pageInfo.getSize();
        return new MarketBaseDataVO(issues, total);
    }

    @Override
    public Issue createIssue(Issue issue) {
        issue.setAddTime(new Date(System.currentTimeMillis()));
        issue.setUpdateTime(new Date(System.currentTimeMillis()));
        issueMapper.insertSelective(issue);
        Issue vo = issueMapper.selectByPrimaryKey(issue.getId());
        return vo;
    }

    @Override
    public Issue issueUpdate(Issue bo) {
        bo.setUpdateTime(new Date(System.currentTimeMillis()));
        issueMapper.updateByPrimaryKeySelective(bo);
        return bo;
    }

    @Override
    public void deleteIssue(Issue bo) {
        bo.setDeleted(true);
        bo.setUpdateTime(new Date(System.currentTimeMillis()));
        issueMapper.updateByPrimaryKeySelective(bo);
    }

    @Override
    public MarketBaseDataVO queryKeywords(Integer page, Integer limit, String sort, String order, String keyword, String url) {
        KeywordExample keywordExample = new KeywordExample();
        KeywordExample.Criteria criteria = keywordExample.createCriteria();
        if (keyword != null) {
            criteria.andKeywordLike("%" + keyword + "%");
        }
        if (url != null) {
            criteria.andUrlLike("%" + url + "%");
        }
        criteria.andDeletedEqualTo(false);
        keywordExample.setOrderByClause(sort + " " + order);
        PageHelper.startPage(page, limit);

        List<Keyword> keywords = keywordMapper.selectByExample(keywordExample);
        PageInfo<Keyword> pageInfo = new PageInfo<>(keywords);
        long total = pageInfo.getSize();
        return new MarketBaseDataVO(keywords, total);
    }

    @Override
    public Keyword createKeyword(Keyword bo) {
        bo.setUpdateTime(new Date(System.currentTimeMillis()));
        bo.setAddTime(new Date(System.currentTimeMillis()));
        keywordMapper.insertSelective(bo);
        return bo;
    }

    @Override
    public Keyword updateKeyword(Keyword bo) {
        bo.setUpdateTime(new Date(System.currentTimeMillis()));
        keywordMapper.updateByPrimaryKeySelective(bo);
        return bo;
    }

    @Override
    public void deleteKeyword(Keyword bo) {
        bo.setDeleted(true);
        bo.setUpdateTime(new Date(System.currentTimeMillis()));
        keywordMapper.updateByPrimaryKeySelective(bo);
    }

    @Override
    public List<MarketCategoryLevelVO> queryCategoryByLevel(String level) {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andLevelEqualTo(level.toUpperCase()).andDeletedEqualTo(false);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        List<MarketCategoryLevelVO> vos = new ArrayList<>();
        for (Category category : categories) {
            vos.add(new MarketCategoryLevelVO(category.getId(), category.getName()));
        }
        return vos;
    }

    @Override
    public List<MarketCategoryListVO> queryCategories() {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.createCriteria().andPidEqualTo(0).andDeletedEqualTo(false);
        List<Category> categories = categoryMapper.selectByExample(categoryExample);
        List<MarketCategoryListVO> vos = new ArrayList<>();
        for (Category category : categories) {
            CategoryExample example = new CategoryExample();
            example.createCriteria().andPidEqualTo(category.getId()).andDeletedEqualTo(false);
            List<Category> children = categoryMapper.selectByExample(example);
            List<MarketCategoryListVO> childrenvo = new ArrayList<>();
            for (Category child : children) {
                //child 转化为vo
                childrenvo.add(new MarketCategoryListVO(child.getId(),
                        child.getName(),
                        child.getKeywords(),
                        child.getDesc(),
                        child.getIconUrl(),
                        child.getPicUrl(),
                        child.getLevel(),
                        child.getDeleted()));
            }
            //category 转化为vo
            vos.add(new MarketCategoryListVO(category.getId(),
                    category.getName(),
                    category.getKeywords(),
                    category.getDesc(),
                    category.getIconUrl(),
                    category.getPicUrl(),
                    category.getLevel(),
                    category.getDeleted(),
                    childrenvo));
        }
        return vos;
    }

    @Override
    public Category createCategory(Category category) {
        category.setAddTime(new Date(System.currentTimeMillis()));
        category.setUpdateTime(new Date(System.currentTimeMillis()));
        categoryMapper.insertSelective(category);
        Category vo = categoryMapper.selectByPrimaryKey(category.getId());
        return vo;
    }

    @Override
    public Category updateCategory(Category bo) {
        bo.setUpdateTime(new Date(System.currentTimeMillis()));
        categoryMapper.updateByPrimaryKeySelective(bo);
        return bo;
    }

    @Override
    public void deleteCategory(MarketCategoryListVO bo) {
        if (bo.getChildren() != null) {
            for (MarketCategoryListVO child : bo.getChildren()) {
                child.setDeleted(true);
                Category category = new Category();
                category.setDeleted(true);
                category.setId(child.getId());
                category.setUpdateTime(new Date(System.currentTimeMillis()));
                categoryMapper.updateByPrimaryKeySelective(category);
            }
        }
        Category ca = new Category();
        ca.setId(bo.getId());
        ca.setDeleted(true);
        ca.setUpdateTime(new Date(System.currentTimeMillis()));
        categoryMapper.updateByPrimaryKeySelective(ca);
    }
}
